<template>
  <div style="display: flex; flex-direction: column">
    <!-- 添加新记录按钮 -->

    <!-- 添加/编辑表单的弹出框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEditMode ? '编辑外购电力热力碳排数据' : '添加外购电力热力碳排数据'"
      @ok="handleSubmit"
      @cancel="closeModal"
    >
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol" layout="horizontal">
        <a-form-item label="能源类型">
          <a-select
            v-model:value="addform.energyTypesId"
            placeholder="请选择"
            style="width: 270px"
          >
            <a-select-option
              v-for="i in Energy"
              :key="i.energyTypesId"
              :value="i.energyTypesId"
            >
              {{ i.energyName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="消耗量">
          <a-input-number
            v-model:value="addform.consumption"
            placeholder="输入消耗量"
            style="width: 270px"
          />
        </a-form-item>

        <a-form-item label="供应商信息">
          <a-select
            v-model:value="addform.supplierId"
            placeholder="请选择"
            style="width: 270px"
          >
            <a-select-option
              v-for="i in Supplierdata"
              :key="i.supplierId"
              :value="i.supplierId"
            >
              {{ i.supplierName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="碳排因子数值">
          <a-input
            v-model:value="addform.emissionFactor"
            placeholder="输入碳排因子数值"
            style="width: 270px"
          />
        </a-form-item>
        <a-form-item label="碳排放量">
          <a-input
            v-model:value="addform.emissionValue"
            placeholder="输入碳排放量"
            style="width: 270px"
          />
        </a-form-item>
        <a-form-item label="时间选择">
          <a-date-picker
            v-model:value="addform.timestamps"
            showTime
            placeholder="选择时间"
            style="width: 270px"
          />
        </a-form-item>

        <a-form-item label="活动类别">
          <a-select
            v-model:value="addform.activityCategoriesId"
            placeholder="请选择"
            style="width: 270px"
          >
            <a-select-option
              v-for="i in activeleibie"
              :key="i.activityCategoriesId"
              :value="i.activityCategoriesId"
            >
              {{ i.activityCategoriesName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="活动类型">
          <a-select
            v-model:value="addform.activityTypesId"
            placeholder="请选择"
            style="width: 270px"
          >
            <a-select-option
              v-for="i in activeleixing"
              :key="i.activityTypesId"
              :value="i.activityTypesId"
            >
              {{ i.activityTypesName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="排放源名称">
          <a-select
            v-model:value="addform.sourceId"
            placeholder="选择车辆类型"
            style="width: 270px"
          >
            <a-select-option v-for="i in data" :key="i.sourceId" :value="i.sourceId">
              {{ i.sourceName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 数据表格 -->
    <a-card title="已添加数据" style="flex: 3">
      <a-button type="primary" @click="showModal('add')" style="margin-bottom: 16px">
        添加新记录
      </a-button>
      <a-table
        :columns="columns"
        :dataSource="dataList"
        rowKey="id"
        :pagination="pagination"
        :loading="tableLoading"
        @change="handleChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span class="action-buttons">
              <a type="link" @click="showModal('edit', record)">编辑</a>
              <a-divider type="vertical" />
              <a type="link" danger @click="handleDelete(record)">删除</a>
            </span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
import { outsourcing } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/outsourcing";
import { selfSupportApi } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/self-support";
import { upstream } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/upstream";
import { energy } from "/@/api/type/Energy";
import { supplier } from "/@/api/type/supplier";
import { smartSentry } from "/@/lib/smart-sentry";
// 初始值和状态
const modalVisible = ref(false);
const isEditMode = ref(false); // 标识当前是添加还是编辑模式
const addform = ref({}); // 表单数据
const dataList = ref([]); // 表格数据
const tableLoading = ref(false);
const total = ref(0);
const activeleibie = ref([]); // 活动类别数据
const activeleixing = ref([]); // 活动类型数据
const labelCol = { span: 6 };
const wrapperCol = { span: 18 };
const Energy = ref([]);
const data = ref([]);
const Supplierdata = ref([]);
// 表格列配置
const columns = [
  { title: "id", dataIndex: "purchasedEnergyEmissionDataId", align: "center" },
  { title: "能源类型", dataIndex: "energyName", align: "center" },
  { title: "消耗量", dataIndex: "consumption", align: "center" },
  { title: "供应商", dataIndex: "supplierName", align: "center" },
  { title: "碳排因子数值", dataIndex: "emissionFactor", align: "center" },
  { title: "碳排放量", dataIndex: "emissionValue", align: "center" },
  { title: "时间", dataIndex: "timestamps", align: "center" },
  { title: "活动类别", dataIndex: "activityCategoriesName", align: "center" },
  { title: "活动类型", dataIndex: "activityTypesName", align: "center" },
  { title: "排放源名称", dataIndex: "sourceName", align: "center" },
  { title: "操作", key: "action", align: "center" },
];

// 分页配置
const pagination = computed(() => ({
  total: total.value,
  pageSize: queryFormState.pageSize,
  current: queryFormState.pageNum,
  showTotal: (total) => `总共${total}项`,
}));

const queryFormState = reactive({
  pageNum: 1,
  pageSize: 10,
});
const queryForm = reactive({ ...queryFormState });

// 数据请求函数
async function queryData() {
  tableLoading.value = true;
  try {
    queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
    queryForm.pageSize = queryFormState.pageSize;
    let queryResult = await outsourcing.query(queryForm);
    dataList.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}
//能源类型
async function queryEnergy() {
  try {
    const energyresult = await energy.query({ pageNum: 1, pageSize: 100 });
    Energy.value = energyresult.data.list;
  } catch (error) {}
}
// 请求活动类别和活动类型数据
async function fetchActivityData() {
  try {
    const activeleibieData = await upstream.queryactivityCategories({
      pageNum: 1,
      pageSize: 100,
    });
    const activeleixingData = await upstream.queryactivityTypes({
      pageNum: 1,
      pageSize: 100,
    });
    activeleibie.value = activeleibieData.data.list;
    activeleixing.value = activeleixingData.data.list;
  } catch (e) {
    console.log(e);
  }
}
//供应商
async function Supplier() {
  try {
    let supplierresult = await supplier.query({ pageNum: 1, pageSize: 100 });
    Supplierdata.value = supplierresult.data.list;
  } catch (error) {}
}
// 请求排量类型数据
async function queryjcdata() {
  try {
    let queryResult = await selfSupportApi.queryData({ pageNum: 1, pageSize: 100 });
    data.value = queryResult.data.list;
  } catch (error) {
    console.log(error);
  }
}
// 显示添加/编辑弹出框
function showModal(mode, record = null) {
  isEditMode.value = mode === "edit";
  modalVisible.value = true;
  if (isEditMode.value) {
    const findIdByName = (list, name, idField, nameField) => {
      const item = list.find((item) => item[nameField] === name);
      return item ? item[idField] : null;
    };
    const energyTypesId = findIdByName(
      Energy.value,
      record.energyName,
      "energyTypesId",
      "energyName"
    );
    const activityCategoriesId = findIdByName(
      activeleibie.value,
      record.activityCategoriesName,
      "activityCategoriesId",
      "activityCategoriesName"
    );
    const activityTypesId = findIdByName(
      activeleixing.value,
      record.activityTypesName,
      "activityTypesId",
      "activityTypesName"
    );
    const sourceId = findIdByName(
      data.value,
      record.sourceName,
      "sourceId",
      "sourceName"
    );
    const supplierId = findIdByName(
      Supplierdata.value,
      record.supplierName,
      "supplierId",
      "supplierName"
    );
    addform.value = {
      ...record,
      energyTypesId: energyTypesId,
      activityCategoriesId: activityCategoriesId,
      activityTypesId: activityTypesId,
      sourceId: sourceId,
      supplierId: supplierId,
      timestamps: dayjs(record.timestamps),
    };
  } else {
    addform.value = {};
  }
}

// 关闭弹出框
function closeModal() {
  modalVisible.value = false;
  addform.value = {};
}

// 提交表单
async function handleSubmit() {
  const addresult = {
    ...addform.value,
    timestamps: dayjs(addform.value.timestamps).format("YYYY-MM-DD HH:mm:ss"),
  };
  try {
    if (isEditMode.value) {
      await outsourcing.update(addresult, addresult.purchasedEmissionDataId); // 编辑模式
    } else {
      await outsourcing.Add(addresult); // 添加模式
    }
    closeModal();
    queryData();
  } catch (error) {
    console.log(error);
  }
}

// 表格分页改变事件
function handleChange(pagination) {
  queryFormState.pageNum = pagination.current; // 更新当前页
  queryFormState.pageSize = pagination.pageSize; // 更新页大小
  queryData(); // 根据分页重新加载数据
}

// 删除记录
async function handleDelete(record) {
  try {
    await outsourcing.DElete(record.purchasedEmissionDataId);
    message.success("删除成功");
    queryData();
  } catch (error) {
    message.error("删除失败");
    console.log(error);
  }
}

// 初始化请求数据
onMounted(() => {
  queryData();
  fetchActivityData();
  queryEnergy();
  queryjcdata();
  Supplier();
});
</script>

<style scoped>
.ant-form-item-label {
  text-align: right;
}

.ant-form-item-control {
  margin-left: 10px;
}
</style>
